/**
 *
 */
package 算法;

/**
 * 求给定的两个数组元素最小间隔距离
 * @Title:
 * @author zhoujie
 * @date 2018年6月5日 上午11:18:50
 *
 */
public class ArtrayMinDistance {
    public static void main(String[] args) {
        int arr[] = {4, 5, 6, 4, 7, 4, 6, 4, 7, 8, 5, 6, 4, 3, 10, 3};
        System.out.println(artrayMinDistance(arr, 3, 3));


    }

    public static int artrayMinDistance(int[] arr, int n1, int n2) {
        int minDistance = -1;//最小距离
        int n1Index = -1;
        int n2Index = -1;
        for (int i = 0; i < arr.length; i++) {
            if (n1 == arr[i]) {
        	/*	 //如果n1和n2都相同 并且n1上一个值已经取了并且n2没值 让给n2
        		 if((n2==n1)&&n1Index!=-1&&n1==arr[n1Index]&&n2Index==-1) {
        			 n2Index=i;
        		 }else {
        			 n1Index=i;
        		 }*/
                n1Index = i;
                if (n2Index != -1) {
                    int jl = Math.abs(i - n2Index);
                    if (minDistance == -1 || jl < minDistance) {
                        minDistance = jl;
                    }
                }
            }

            if (n2 == arr[i]) {
                n2Index = i;
                if (n1Index != -1) {
                    int jl = Math.abs(i - n1Index);
                    if (minDistance == -1 || jl < minDistance) {
                        minDistance = jl;
                    }
                }
            }
        }
        return minDistance;
    }
}
